﻿// Copyright 2008 William P. Hickey Jr. and William U. Walker
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//     
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//  
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using AgwpePort.Aprs;

namespace CSReporter
{
    public partial class CustomizeDialog : Form
    {
        private ConfigList configure;
        private StatusTextList statusText;

        #region " Constructor and Load event handler "
        public CustomizeDialog()
        {
            InitializeComponent();
            // Load data into the ConfigList object.
            configure = ConfigList.GetConfigList();
            // Get the StatusTextList object.
            statusText = StatusTextList.GetStatusTextList();
            // Bind data entry components to data properties.
            SetDatabindings();
        }

        private void CustomizeDialog_Load(object sender, System.EventArgs e)
        {
            KmlFileInit();
            PacketRadioInit();
        }
        #endregion
        #region " Button and MenuItem Click event handlers "
        private void OK_Button_Click(object sender, System.EventArgs e)
        {
            KmlFileUpdate();
            PacketRadioUpdate();
            // Write the modified configuration information to disk
            configure.WriteXml();
            statusText.WriteXml(configure[0].DataDir + @"\statustext.xml");
            // Close and tell the parent object the OK button was clicked
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void Cancel_Button_Click(object sender, System.EventArgs e)
        {
            // Read the original configuration information from disk
            configure.ReadXml();
            statusText.ReadXml(configure[0].DataDir + @"\statustext.xml");
            // Close and tell the parent object the Cancel button was clicked
            DialogResult = DialogResult.Cancel;
        }

        private void FileDialogButton_Click(object sender, System.EventArgs e)
        {
            if(DataFolderDialog.ShowDialog() == DialogResult.OK)
                DataDirTextBox.Text = DataFolderDialog.SelectedPath;
        }

        private void kmlFileDialogButton_Click(object sender, System.EventArgs e)
        {
            if(DataFolderDialog.ShowDialog() == DialogResult.OK)
                kmlFileLocationTextBox.Text = DataFolderDialog.SelectedPath;
        }

        private void redIconDialogButton_Click(object sender, System.EventArgs e)
        {
            if(DataFolderDialog.ShowDialog() == DialogResult.OK)
                redIconTextBox.Text = DataFolderDialog.SelectedPath;
        }

        private void yellowIconDialogButton_Click(object sender, System.EventArgs e)
        {
            if(DataFolderDialog.ShowDialog() == DialogResult.OK)
                yellowIconTextBox.Text = DataFolderDialog.SelectedPath;
        }

        private void greenIconDialogButton_Click(object sender, System.EventArgs e)
        {
            if(DataFolderDialog.ShowDialog() == DialogResult.OK)
                greenIconTextBox.Text = DataFolderDialog.SelectedPath;
        }

        private void whiteIconDialogButton_Click(object sender, System.EventArgs e)
        {
            if(DataFolderDialog.ShowDialog() == DialogResult.OK)
                whiteIconTextBox.Text = DataFolderDialog.SelectedPath;
        }

        private void createNetworkLinkButton_Click(object sender, System.EventArgs e)
        {
            WriteNetworkLink();
        }
        #endregion
        #region " Additional methods and handlers "

        private void eventNameTextBox_TextChanged(object sender, System.EventArgs e)
        {
            if(eventNameTextBox.Text.Length > 0)
            {
                createNetworkLinkButton.Enabled = true;
                autoUpdateCheckBox.Enabled = true;
            }
            else
            {
                autoUpdateCheckBox.Checked = false;
                createNetworkLinkButton.Enabled = false;
                autoUpdateCheckBox.Enabled = false;
            }
        }

        private void ftpKMLCheckBox_CheckedChanged(object sender, System.EventArgs e)
        {
            ftpInfoGroupBox.Enabled = ftpKMLCheckBox.Checked;
        }

        private void latitudeTextBox_Leave(object sender, System.EventArgs e)
        {
            Coordinate lat = new Coordinate(latitudeTextBox.Text);

            if (Convert.ToDouble(lat.ToDegrees()) != 0)
            {
                if (lat.Degrees < 0)
                    lat.Degrees *= -1;
                latitudeTextBox.Text = lat.ToDecMinuteString();
            }
            else
            {
                if (latitudeTextBox.Text.Trim().Length > 0)
                    MessageBox.Show("Invalid coordinate format.\nValid formats are:\nTwo digit degrees\n-or-\nDecimal degrees\n-or-\nDegrees and decimal minutes\nExamples:\n32 or 32.1990833 or 32 11.945", "Format Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void longitudeTextBox_Leave(object sender, System.EventArgs e)
        {
            Coordinate lon = new Coordinate(longitudeTextBox.Text);

            if (Convert.ToDouble(lon.ToDegrees()) != 0)
            {
                if (lon.Degrees > 0)
                    lon.Degrees *= -1;
                longitudeTextBox.Text = lon.ToDecMinuteString();
            }
            else
            {
                if (longitudeTextBox.Text.Trim().Length > 0)
                    MessageBox.Show("Invalid coordinate format.\nValid formats are:\nThree digit degrees\n-or-\nDecimal degrees\n-or-\nDegrees and decimal minutes\nExamples:\n110 or 110.873220 or 110 52.393", "Format Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void WindowsAuthCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            SqlServerLoginTextBox.Enabled = !WindowsAuthCheckBox.Checked;
            SqlServerPasswordTextBox.Enabled = !WindowsAuthCheckBox.Checked;
        }

        private void SqlServerTextBox_TextChanged(object sender, EventArgs e)
        {
            if (SqlServerTextBox.Text.Trim().Length > 0 & SqlDatabaseTextBox.Text.Trim().Length > 0)
                SqlServerCheckBox.Enabled = true;
            else
            {
                SqlServerCheckBox.Checked = false;
                SqlServerCheckBox.Enabled = false;
            }
        }

        private void KmlFileInit()
        {
            rangeNumericUpDown.Value = (decimal)configure[0].KmlRange;
            flyToViewCheckBox.Checked = configure[0].KmlFlyToView;
            refreshIntervalNumericUpDown.Value = configure[0].KmlRefreshInterval;
            kmlFileLocationTextBox.Text = configure[0].KmlFileLocation;
            redIconTextBox.Text = configure[0].KmlRedIcon;
            yellowIconTextBox.Text = configure[0].KmlYellowIcon;
            greenIconTextBox.Text = configure[0].KmlGreenIcon;
            whiteIconTextBox.Text = configure[0].KmlWhiteIcon;
            autoUpdateCheckBox.Checked = configure[0].SaveToKml;
            eventNameTextBox.Text = configure[0].EventName;
            eventNameTextBox_TextChanged(this, null);
            ftpHostNameTextBox.Text = configure[0].FtpKmlHost;
            ftpPathTextBox.Text = configure[0].FtpKmlPath;
            ftpUserTextBox.Text = configure[0].FtpKmlLogin;
            ftpPasswordTextBox.Text = configure[0].FtpKmlPassword;
            ftpPortNumericUpDown.Value = configure[0].FtpKmlPort;
            ftpKMLCheckBox.Checked = configure[0].FtpKmlPublish;
            ftpKMLCheckBox_CheckedChanged(this, null);
        }

        private void PacketRadioInit()
        {
            switch(configure[0].InterfaceType)
            {
                case PacketControlType.Disabled:
                    disablePacketRadioButton.Checked = true;
                    break;
                case PacketControlType.AGWPE:
                    AgwpeRadioButton.Checked = true;
                    break;
                case PacketControlType.SerialPort:
                    DirectRadioButton.Checked = true;
                    break;
            }
            agwHostTextBox.Text = configure[0].AgwHost;
            agwPortUpDown.Value = configure[0].AgwPort;
            agwRadioUpDown.Value = configure[0].AgwVhfUhfRadio;
            CallSignTextBox.Text = configure[0].CallSign;
            beaconIntervalUpDown.Value = configure[0].BeaconInterval;
            beaconCheckBox.Checked = configure[0].BeaconOnStart;
            beaconTextBox.Text = configure[0].BeaconText;
            digiPathTextBox.Text = configure[0].DigiPath;
            txPowerComboBox.SelectedIndex = configure[0].TxPower;
            haatComboBox.SelectedIndex = configure[0].Haat;
            antGainComboBox.SelectedIndex = configure[0].AntGain;
            antDirComboBox.SelectedIndex = configure[0].AntDirectivity;
            latitudeTextBox.Text = (new Coordinate(configure[0].Latitude)).ToDecMinuteString();
            longitudeTextBox.Text = (new Coordinate(configure[0].Longitude)).ToDecMinuteString();
        }

        private void KmlFileUpdate()
        {
            configure[0].KmlRange = (double)rangeNumericUpDown.Value;
            configure[0].KmlFlyToView = flyToViewCheckBox.Checked;
            configure[0].KmlRefreshInterval = (int)refreshIntervalNumericUpDown.Value;
            configure[0].KmlFileLocation = kmlFileLocationTextBox.Text.Trim();
            configure[0].KmlRedIcon = redIconTextBox.Text.Trim();
            configure[0].KmlYellowIcon = yellowIconTextBox.Text.Trim();
            configure[0].KmlGreenIcon = greenIconTextBox.Text.Trim();
            configure[0].KmlWhiteIcon = whiteIconTextBox.Text.Trim();
            configure[0].SaveToKml = autoUpdateCheckBox.Checked;
            configure[0].EventName = eventNameTextBox.Text.Trim();
            configure[0].FtpKmlHost = ftpHostNameTextBox.Text.Trim();
            configure[0].FtpKmlPath = ftpPathTextBox.Text.Trim();
            configure[0].FtpKmlLogin = ftpUserTextBox.Text.Trim();
            configure[0].FtpKmlPassword = ftpPasswordTextBox.Text.Trim();
            configure[0].FtpKmlPort = (int)ftpPortNumericUpDown.Value;
            configure[0].FtpKmlPublish = ftpKMLCheckBox.Checked;
        }

        private void PacketRadioUpdate()
        {
            if(disablePacketRadioButton.Checked)
                configure[0].InterfaceType = PacketControlType.Disabled;
            else if(AgwpeRadioButton.Checked)
                configure[0].InterfaceType = PacketControlType.AGWPE;
            else if(DirectRadioButton.Checked)
                configure[0].InterfaceType = PacketControlType.SerialPort;
            configure[0].AgwHost = agwHostTextBox.Text;
            configure[0].AgwPort = (int)agwPortUpDown.Value;
            configure[0].AgwVhfUhfRadio = (int)agwRadioUpDown.Value;
            configure[0].CallSign = CallSignTextBox.Text;
            configure[0].BeaconInterval = (int)beaconIntervalUpDown.Value;
            configure[0].BeaconOnStart = beaconCheckBox.Checked;
            configure[0].BeaconText = beaconTextBox.Text;
            configure[0].DigiPath = digiPathTextBox.Text;
            configure[0].TxPower = txPowerComboBox.SelectedIndex;
            configure[0].Haat = haatComboBox.SelectedIndex;
            configure[0].AntGain = antGainComboBox.SelectedIndex;
            configure[0].AntDirectivity = antDirComboBox.SelectedIndex;
            configure[0].Latitude = (new Coordinate(latitudeTextBox.Text)).ToDegrees();
            configure[0].Longitude = (new Coordinate(longitudeTextBox.Text)).ToDegrees();
        }

        private void WriteNetworkLink()
        {
            try
            {
                if (Directory.Exists(Path.GetDirectoryName(kmlFileLocationTextBox.Text.Trim())))
                {
                    try
                    {
                        StreamWriter fileStream;
                        string fullLinkPath;

                        fullLinkPath = Path.GetFullPath(kmlFileLocationTextBox.Text.Trim()).TrimEnd('\\') + "\\" + eventNameTextBox.Text.Trim() + ".kml";
                        // Create a new StreamWriter object to write to the file with.
                        fileStream = new StreamWriter(fullLinkPath);
                        // Write the network link file.
                        fileStream.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
                                         "<kml xmlns=\"http://earth.google.com/kml/2.1\">\r\n" +
                                         "<Document>\r\n" +
                                         "    <NetworkLink>\r\n");
                        if (flyToViewCheckBox.Checked)
                        {
                            fileStream.Write("        <flyToView>1</flyToView>\r\n");
                        }
                        fileStream.Write("        <Link>\r\n" +
                                         "            <href>" + eventNameTextBox.Text.Trim() + "_features.kml</href>\r\n" +
                                         "            <refreshMode>onInterval</refreshMode>\r\n" +
                                         "            <refreshInterval>" + refreshIntervalNumericUpDown.Value.ToString() + "</refreshInterval>\r\n" +
                                         "        </Link>\r\n" +
                                         "    </NetworkLink>\r\n" +
                                         "</Document>\r\n" +
                                         "</kml>");
                        // Close the fileStream.
                        fileStream.Close();

                        //if (ftpKMLCheckBox.Checked & ftpHostNameTextBox.Text.Trim().Length > 0 & ftpPathTextBox.Text.Trim().Length > 0 & ftpUserTextBox.Text.Trim().Length > 0 & ftpPasswordTextBox.Text.Trim().Length > 0)
                        //{
                        //    FTP ftpKML;

                        //    try
                        //    {
                        //        ftpKML = new FTP(ftpHostNameTextBox.Text.Trim, ftpPathTextBox.Text.Trim, ftpUserTextBox.Text.Trim, ftpPasswordTextBox.Text.Trim, ftpPortNumericUpDown.Value);

                        //        // Attempt to log into the FTP Server.
                        //        if (ftpKML.Login())
                        //        {
                        //            // Set the FTP mode to binary
                        //            ftpKML.SetBinaryMode(true);

                        //            // Upload the network link file.
                        //            ftpKML.UploadFile(fullLinkPath);
                        //            ftpKML.CloseConnection();
                        //        }
                        //    }
                        //    catch (Exception ex)
                        //    {
                        //        MessageBox.Show(ex.Message);
                        //    }
                        //}
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("The KML File Location is invalid.  Please choose a valid file location and try again.", "Invalid File Location", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (System.ArgumentException e)
            {
                MessageBox.Show("The KML File Location is invalid.  Please choose a valid file location and try again.", "Invalid File Location", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        #endregion
        #region " Data bindings "
        private void SetDatabindings()
        {
            // General configuration
            SqlServerTextBox.DataBindings.Add("Text", configure, "SqlServerName");
            SqlDatabaseTextBox.DataBindings.Add("Text", configure, "SqlDatabase");
            SqlServerLoginTextBox.DataBindings.Add("Text", configure, "SqlLogin");
            SqlServerPasswordTextBox.DataBindings.Add("Text", configure, "SqlPassword");
            WindowsAuthCheckBox.DataBindings.Add("Checked", configure, "UseWindowsAuth");
            SqlServerCheckBox.DataBindings.Add("Checked", configure, "SaveToSql");
            DataDirTextBox.DataBindings.Add("Text", configure, "DataDir");
            NoSoundCheckBox.DataBindings.Add("Checked", configure, "NoSound");
            // Packet configuration
            AgwConnectCheckBox.DataBindings.Add("Checked", configure, "ConnectOnStart");
            ReportToTextBox.DataBindings.Add("Text", configure, "ReportToCall");
            // Status label text
            status1TextBox.DataBindings.Add("Text", statusText, "Status1");
            status1RTextBox.DataBindings.Add("Text", statusText, "Status1R");
            status1YTextBox.DataBindings.Add("Text", statusText, "Status1Y");
            status1GTextBox.DataBindings.Add("Text", statusText, "Status1G");
            status1WTextBox.DataBindings.Add("Text", statusText, "Status1W");
            status2TextBox.DataBindings.Add("Text", statusText, "Status2");
            status2RTextBox.DataBindings.Add("Text", statusText, "Status2R");
            status2YTextBox.DataBindings.Add("Text", statusText, "Status2Y");
            status2GTextBox.DataBindings.Add("Text", statusText, "Status2G");
            status2WTextBox.DataBindings.Add("Text", statusText, "Status2W");
            status3TextBox.DataBindings.Add("Text", statusText, "Status3");
            status3RTextBox.DataBindings.Add("Text", statusText, "Status3R");
            status3YTextBox.DataBindings.Add("Text", statusText, "Status3Y");
            status3GTextBox.DataBindings.Add("Text", statusText, "Status3G");
            status3WTextBox.DataBindings.Add("Text", statusText, "Status3W");
            status4TextBox.DataBindings.Add("Text", statusText, "Status4");
            status4RTextBox.DataBindings.Add("Text", statusText, "Status4R");
            status4YTextBox.DataBindings.Add("Text", statusText, "Status4Y");
            status4GTextBox.DataBindings.Add("Text", statusText, "Status4G");
            status4WTextBox.DataBindings.Add("Text", statusText, "Status4W");
            status5TextBox.DataBindings.Add("Text", statusText, "Status5");
            status5RTextBox.DataBindings.Add("Text", statusText, "Status5R");
            status5YTextBox.DataBindings.Add("Text", statusText, "Status5Y");
            status5GTextBox.DataBindings.Add("Text", statusText, "Status5G");
            status5WTextBox.DataBindings.Add("Text", statusText, "Status5W");
            status6TextBox.DataBindings.Add("Text", statusText, "Status6");
            status6RTextBox.DataBindings.Add("Text", statusText, "Status6R");
            status6YTextBox.DataBindings.Add("Text", statusText, "Status6Y");
            status6GTextBox.DataBindings.Add("Text", statusText, "Status6G");
            status6WTextBox.DataBindings.Add("Text", statusText, "Status6W");
            status7TextBox.DataBindings.Add("Text", statusText, "Status7");
            status7RTextBox.DataBindings.Add("Text", statusText, "Status7R");
            status7YTextBox.DataBindings.Add("Text", statusText, "Status7Y");
            status7GTextBox.DataBindings.Add("Text", statusText, "Status7G");
            status7WTextBox.DataBindings.Add("Text", statusText, "Status7W");
            status8TextBox.DataBindings.Add("Text", statusText, "Status8");
            status8RTextBox.DataBindings.Add("Text", statusText, "Status8R");
            status8YTextBox.DataBindings.Add("Text", statusText, "Status8Y");
            status8GTextBox.DataBindings.Add("Text", statusText, "Status8G");
            status8WTextBox.DataBindings.Add("Text", statusText, "Status8W");
            status9TextBox.DataBindings.Add("Text", statusText, "Status9");
            status9RTextBox.DataBindings.Add("Text", statusText, "Status9R");
            status9YTextBox.DataBindings.Add("Text", statusText, "Status9Y");
            status9GTextBox.DataBindings.Add("Text", statusText, "Status9G");
            status9WTextBox.DataBindings.Add("Text", statusText, "Status9W");
            status10TextBox.DataBindings.Add("Text", statusText, "Status10");
            status10RTextBox.DataBindings.Add("Text", statusText, "Status10R");
            status10YTextBox.DataBindings.Add("Text", statusText, "Status10Y");
            status10GTextBox.DataBindings.Add("Text", statusText, "Status10G");
            status10WTextBox.DataBindings.Add("Text", statusText, "Status10W");
            status11TextBox.DataBindings.Add("Text", statusText, "Status11");
            status11RTextBox.DataBindings.Add("Text", statusText, "Status11R");
            status11YTextBox.DataBindings.Add("Text", statusText, "Status11Y");
            status11GTextBox.DataBindings.Add("Text", statusText, "Status11G");
            status11WTextBox.DataBindings.Add("Text", statusText, "Status11W");
            status12TextBox.DataBindings.Add("Text", statusText, "Status12");
            status12RTextBox.DataBindings.Add("Text", statusText, "Status12R");
            status12YTextBox.DataBindings.Add("Text", statusText, "Status12Y");
            status12GTextBox.DataBindings.Add("Text", statusText, "Status12G");
            status12WTextBox.DataBindings.Add("Text", statusText, "Status12W");
            status13TextBox.DataBindings.Add("Text", statusText, "Status13");
            status13RTextBox.DataBindings.Add("Text", statusText, "Status13R");
            status13YTextBox.DataBindings.Add("Text", statusText, "Status13Y");
            status13GTextBox.DataBindings.Add("Text", statusText, "Status13G");
            status13WTextBox.DataBindings.Add("Text", statusText, "Status13W");
            status14TextBox.DataBindings.Add("Text", statusText, "Status14");
            status14RTextBox.DataBindings.Add("Text", statusText, "Status14R");
            status14YTextBox.DataBindings.Add("Text", statusText, "Status14Y");
            status14GTextBox.DataBindings.Add("Text", statusText, "Status14G");
            status14WTextBox.DataBindings.Add("Text", statusText, "Status14W");
            status15TextBox.DataBindings.Add("Text", statusText, "Status15");
            status15RTextBox.DataBindings.Add("Text", statusText, "Status15R");
            status15YTextBox.DataBindings.Add("Text", statusText, "Status15Y");
            status15GTextBox.DataBindings.Add("Text", statusText, "Status15G");
            status15WTextBox.DataBindings.Add("Text", statusText, "Status15W");
            status16TextBox.DataBindings.Add("Text", statusText, "Status16");
            status16RTextBox.DataBindings.Add("Text", statusText, "Status16R");
            status16YTextBox.DataBindings.Add("Text", statusText, "Status16Y");
            status16GTextBox.DataBindings.Add("Text", statusText, "Status16G");
            status16WTextBox.DataBindings.Add("Text", statusText, "Status16W");
        }
        #endregion
    }
}
